//
//  SignViewController.m
//  便签
//
//  Created by  on 2022/9/30.
//

#import "SignViewController.h"
#import "EditCell.h"
#import <SnapKit/SnapKit-umbrella.h>
@interface SignViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UILabel *typeName;
@property (strong, nonatomic) UIButton *rightBtn;
@property (strong, nonatomic) IBOutlet BaseTextField *input;
@property (strong, nonatomic) NSMutableArray *array;
@property (assign, nonatomic) NSInteger  selectNum;

@end

@implementation SignViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
- (void)initUI{
    self.array = [NSMutableArray array];
    NSMutableArray *imgs = [NSMutableArray array];
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"account"),bg_sqlValue(APP.user.account)];
    //    [SignModel bg_findAsync:nil where:where complete:^(NSArray * _Nullable array) {
    //        if (array.count > 0) {
    //            dispatch_async(dispatch_get_main_queue(), ^{
    //                for (SignModel *m in array) {
    //                    [imgs addObject:m.cover];
    //                }
    //                self.array = imgs;
    //            });
    //        }
    //    }];
    
    NSArray *array = @[@"card-1",@"card-2",@"card-3",@"card-4",@"card-5",@"card-6"];
    for (NSString *name in array) {
        UIImage *img = [UIImage imageNamed:name];
        NSData *data = UIImageJPEGRepresentation(img, 0.5);
        [imgs addObject:data];
    }
    self.array = imgs;
    
    if (self.model == nil) {
        self.model = [SignModel new];
        self.model.account = APP.user.account;
        self.model.ID = [NSString stringWithFormat:@"%d",(int)[SignModel bg_count:nil where:where] + 1];
    }
    self.selectNum = self.array.count;
    self.input.text = self.model.title;
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightBtn.tag = 205;
    self.rightBtn.frame = CGRectMake(0, StuBarHight + 5, 40, 34);
    [self.rightBtn addTarget:self action:@selector(actionForBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn setTitleColor:[UIColor colorHex:@"#1A1A1A"] forState:UIControlStateNormal];
    [self.rightBtn setImage:[UIImage imageNamed:@"选中_黑色"] forState:UIControlStateNormal];
    [self.rightBtn setImage:[UIImage imageNamed:@"选中_橘色"] forState:UIControlStateSelected];
    UIBarButtonItem *item =[[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    [self.collectionView registerNib:[EditCell nib] forCellWithReuseIdentifier:[EditCell ID]];
    NSLayoutConstraint *top = [self.collectionView a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.typeName a2:NSLayoutAttributeBottom c:0];
    NSLayoutConstraint *left = [self.collectionView a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:0];
    NSLayoutConstraint *right = [self.collectionView a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:0];
    NSLayoutConstraint *bottom = [self.collectionView a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeBottom c:0];
    [self.view addConstraints:@[top,left,right,bottom]];
    
    UIView * view = [[UIView alloc] init];
    [self.view addSubview:view];
  
}

- (IBAction)actionForBtn:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.model.title = self.input.text;
    if (self.model.title.length <= 0) {
        return [Toast msg:LS(@"标题不能为空")];
    }else if(self.model.cover.length <= 0){
        return [Toast msg:LS(@"请选择一个封面")];
    }
    //    if (self.model.title.length > 0) {
    //        NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"title"),bg_sqlValue(self.model.title)];
    //        [SignModel bg_delete:nil where:where];
    //    }
    [self.model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self backBtnAction];
            [[NSNotificationCenter defaultCenter] postNotificationName:notifySignUpdate object:nil];
        });
    }];
}
- (void)setArray:(NSMutableArray *)array{
    if (_array != array) {
        _array = array;
        [self.collectionView reloadData];
    }
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    self.model.cover = data;
    [self.array addObject:data];
    [self.collectionView reloadData];
    [[NSUserDefaults standardUserDefaults] setValue:self.array forKey:localCoverKey];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  self.array.count + 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EditCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[EditCell ID] forIndexPath:indexPath];
    cell.btnRight.constant = 12;
    cell.btnTop.constant = 12;
    cell.btn.userInteractionEnabled = NO;
    cell.btn.selected = self.selectNum == indexPath.row;
    [cell.btn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
    [cell.btn setImage:[UIImage imageNamed:@"选中_橘色"] forState:UIControlStateSelected];
    cell.img.image = indexPath.row == self.array.count ? [UIImage imageNamed:@"add"] : [UIImage imageWithData:self.array[indexPath.row]];
    cell.btn.hidden = self.array.count == indexPath.row;
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WS(self)
    if (indexPath.row == self.array.count) {
        SheetViewController *vc = [SheetViewController new];
        vc.withCancel = NO;
        vc.array = @[@"相机",@"从图库中选择"];
        vc.block = ^(int index, NSString * _Nonnull text) {
            [weakself ImagePicker: index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else{
        self.selectNum = indexPath.row;
        self.model.cover = self.array[indexPath.row];
    }
    [collectionView reloadData];
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat w = (SCREEN_WIDTH - 20 * 3) / 2;
    CGFloat h = 203 / 153.0 * w;
    return  CGSizeMake(w,h);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(20, 20, 20, 20);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}

@end
